package com.ruoyi.api.user;

import com.crm.sms.SMSResult;
import com.crm.sms.biz.SMSClient;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.UserPwd;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.core.redis.RedisKey;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.GeneratorUtil;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.CrmGroup;
import com.ruoyi.system.domain.SysGroup;
import com.ruoyi.system.domain.SysUserOnline;
import com.ruoyi.system.service.ICrmGroupService;
import com.ruoyi.system.service.ISysGroupService;
import com.ruoyi.system.service.ISysUserOnlineService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/crm")
public class CrmLoginController {
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private SMSClient smsClient;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysUserOnlineService userOnlineService;

    @Autowired
    private ISysGroupService sysGroupService;
    @Autowired
    private ICrmGroupService crmGroupService;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody SysUser user)
    {
        String phonenumber = user.getPhonenumber();
        String password = user.getPassword();
        String cid = user.getCid();

        if(StringUtils.isEmpty(phonenumber)){
            return AjaxResult.error("未填写，登陆用户名");
        }
        if(StringUtils.isEmpty(password)){
            return AjaxResult.error("未填写，登陆密码");
        }
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.crmLogin(phonenumber, password,cid);
        System.out.println("cid==="+user.getCid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 手机号是否重复   获取验证码
     * @return
     */
    @GetMapping("/checkPhoneUnique")
    public AjaxResult checkPhoneUnique(String phonenumber){
        SysUser user=new SysUser();
        user.setPhonenumber(phonenumber);
        user.setUserName(phonenumber);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("手机号码已存在");
        }
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            return AjaxResult.error("登录账号已存在");
        }
        //获取手机验证码
        String verifyCode = GeneratorUtil.genSixVerifyCode();
        SMSResult res = smsClient.sendRegisterVerify(user.getUserName(), verifyCode);
        if (res.isSucc()) {
            //五分钟 验证码过期
            redisCache.setCacheObject(RedisKey.REGISTRATION_PHONE_CODE + user.getUserName(),verifyCode,300, TimeUnit.SECONDS);
        } else {
            return AjaxResult.error(res.getMsg());
        }
        return AjaxResult.success("success");
    }

    /**
     * 新增用户
     */
    @PostMapping("/registration")
    public AjaxResult registration(@RequestBody SysUser user)
    {
        user.setUserName(user.getPhonenumber());
        if(!redisCache.isHasKey(RedisKey.REGISTRATION_PHONE_CODE + user.getUserName())){
            return AjaxResult.error("验证码过期");
        }
        String code =(String) redisCache.getCacheObject(RedisKey.REGISTRATION_PHONE_CODE + user.getUserName());
        if(!code.trim().equals(user.getPhoneCode().trim())){
            return AjaxResult.error("验证码错误");
        }
        //设置默认的 用户角色数据  默认部门和用户角色
        user.setDeptId(110L);
        Long [] roleIds={3L};
        user.setRoleIds(roleIds);
        Long [] ostIds={4L};
        user.setPostIds(ostIds);
        user.setNickName(user.getUserName());
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        int id=userService.insertUser(user);
        if(id>0){
            CrmGroup crmGroup=new CrmGroup();
            SysGroup sysGroup=new SysGroup();
            List<SysGroup> sysGroupList=sysGroupService.selectSysGroupList(sysGroup);
            List<CrmGroup> crmGroupList=changeGroup(sysGroupList,user.getUserId());
            crmGroupService.batchInsert(crmGroupList,user.getUserId());
        }
        //生成分组
         return id > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    public List<CrmGroup> changeGroup(List<SysGroup> sysGroupList,Long userId){
        List<CrmGroup> crmGroupList=new ArrayList<CrmGroup>();
        for (SysGroup sysGroup:sysGroupList){
            CrmGroup crmGroup=new CrmGroup();
            crmGroup.setGroupName(sysGroup.getGroupName());
            crmGroup.setCreateUser(userId);
            crmGroup.setCreateTime(new Date());
            crmGroupList.add(crmGroup);
        }
        return crmGroupList;
    }
    /**
     * 修改密码
     */
    @PostMapping("/updatePassword")
    public AjaxResult updatePassword(@RequestBody UserPwd userPwd){
        String oldPassword = userPwd.getOpwd();
        String newPassword = userPwd.getNpwd();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }

    /**
     * 忘记密码-校验账号-发送验证码
     * @param phonenumber
     * @return
     */
    @GetMapping("fPwdCheckCode")
    public AjaxResult fPwdCheckCode(String phonenumber){
        SysUser user=new SysUser();
        user.setUserName(phonenumber);
        if (!UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            return AjaxResult.error("用户'" + user.getUserName() + "'不存在，请注册");
        }
        //获取手机验证码
        String verifyCode = GeneratorUtil.genSixVerifyCode();
        SMSResult res = smsClient.sendResetPasswordVerify(user.getUserName(), verifyCode);
        if (res.isSucc()) {
            //五分钟 验证码过期
            redisCache.setCacheObject(RedisKey.FROGETPWD_PHONE_CODE + user.getUserName(),verifyCode,300, TimeUnit.SECONDS);
            return AjaxResult.success("success");
        }
            return AjaxResult.error(res.getMsg());

    }

    /**
     * 忘记密码
     * @return
     */
    @PostMapping("/forgetPassword")
    public AjaxResult forgetPassword(@RequestBody SysUser user){
        user.setUserName(user.getPhonenumber());
        if(!redisCache.isHasKey(RedisKey.FROGETPWD_PHONE_CODE + user.getUserName())){
            return AjaxResult.error("验证码过期");
        }
        String code =(String) redisCache.getCacheObject(RedisKey.FROGETPWD_PHONE_CODE + user.getUserName());
        if(!code.trim().equals(user.getPhoneCode().trim())){
            return AjaxResult.error("验证码错误");
        }
        return userService.resetUserPwd(user.getUserName(), SecurityUtils.encryptPassword(user.getPassword())) > 0 ? AjaxResult.success("密码重置成功"): AjaxResult.error("密码重置失败");
    }



    @GetMapping("/getUserMessage")
    public AjaxResult getUserMessage(){
        AjaxResult ajax = AjaxResult.success();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        user.setDept(null);
        user.setRoles(null);
        ajax.put("data",user);
        return ajax;
    }

    @PostMapping("/updateUserMessage")
    public AjaxResult updateUserMessage(@RequestBody SysUser user){
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        user.setUserId(userId);
        int i = userService.updateUser(user);
        SysUser sysUser = userService.selectUserById(userId);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        loginUser.setUser(sysUser);
        tokenService.setLoginUser(loginUser);
        return i > 0?AjaxResult.success("修改成功"):AjaxResult.success("修改失败");
    }

    @GetMapping("/logout")
    public AjaxResult logout(){
        LoginUser user = SecurityUtils.getLoginUser();
        SysUserOnline sysUserOnline = userOnlineService.selectOnlineByUserName(user.getUser().getPhonenumber(), user);
        String tokenId = sysUserOnline.getTokenId();
        redisCache.deleteObject(Constants.LOGIN_TOKEN_KEY + tokenId);
        return AjaxResult.success();
    }
}
